package munyorderweb;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import munyorderweb_DB.Change_Bean;
import munyorderweb_DB.DB_manager;

public class Category_change extends HttpServlet {
	int nom;
	String sql;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		order(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		order(req,resp);
	}

	protected void order(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html; charset=utf-8");
		HttpSession session = req.getSession();
		ArrayList<Change_Bean> list = (ArrayList<Change_Bean>)session.getAttribute("Category");
		//session.removeAttribute("Category");

		Connection con = null;
		sql = "select * from category";

		try{
			//DB接続　SQL結果取得
			con = DB_manager.getConnection();
			Statement str = con.createStatement();

			ArrayList<Change_Bean> db = new ArrayList<Change_Bean>();
System.out.println("Bean前");
			if(req.getParameter("Yes") != null){

				//Change_Bean型でArrayListに投入
				for(int i=0; i < list.size(); i++){
					Change_Bean change = list.get(i);
					if(change.getCategory_no() == 0){
						str.executeUpdate("insert into category (category_name, category_use) "
								+ " values('" + change.getCategory_name() + "', 0)");
					}else if(change.getCategory_no() > 0){
						if(change.getCategory_name() == ""){
							str.executeUpdate("delete from category where category_no = " + change.getCategory_no());
						}else{
						str.executeUpdate("Update category set category_name = '"+ change.getCategory_name()
								+ "' where Category_no = " + change.getCategory_no());
						}
					}
				}

				Statement stm = con.createStatement();
				ResultSet rs = stm.executeQuery(sql);

				while(rs.next()){
					Change_Bean T_chan = new Change_Bean();
					T_chan.setCategory_no(rs.getInt("Category_no"));
					T_chan.setCategory_name(rs.getString("Category_name"));
					db.add(T_chan);
				}

				//表示用Jspファイルを呼出して画面上に表示
				req.setAttribute("kakutei", db);
				RequestDispatcher dispatcher = req.getRequestDispatcher("kakutei.jsp");
				dispatcher.include(req, resp);
			}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			try{
				if(con != null){
					con.close();
				}
			}catch (SQLException e){
				e.printStackTrace();
			}
		}
	}
}
